<template>
  <a-card>
    <p style="font-size: 18px; text-align: center">生产材料退库</p>
    <br />
    <!-- 单据 -->
    <a-form-model ref="ruleForm" :model="Form" v-bind="layout" :rules="rules"
      ><!-- 顶部的信息 -->
      <a-row>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="单据号">
            <a-input
              style="border: 0"
              v-model="Form.document"
              disabled
            ></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="单据日期">
            <a-date-picker
              v-model="Form.document_date"
              type="date"
              placeholder="请选择时间"
              style="width: 100%"
              @change="
                (a, b) => {
                  this.Form.a = a;
                  this.Form.document_date = b;
                  this.Form.balance = b;
                  this.dataSource.forEach((item, index) => {
                    this.dataSource[index].deliveryDate = b;
                  });
                }
              "
            />
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="仓库名称" prop="depotName">
            <a-select
              v-model="Form.depotName"
              showSearch
              style="width: 100%"
              @change="formDepotNameSelectChange"
            >
              <a-select-option
                v-for="item in storageList"
                :key="item.depotId"
                :value="
                  item.depotId + '|' + item.depotNo + '|' + item.depotName
                "
                >{{ item.depotNo }} {{ item.depotName }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="8" :sm="24" :xs="24">
          <a-form-model-item
            label="产成品仓库"
            prop="finishedProductDepot_dictText"
          >
            <a-select
              v-model="Form.finishedProductDepot_dictText"
              showSearch
              style="width: 100%"
              @change="finishedProductDepotChange"
            >
              <!-- @change="
                  (val) => {
                    const arr = val.split('|');
                    this.form.applicationDepot_dictText = arr[2];
                    this.form.depotId = arr[0];
                  }
                " -->
              <a-select-option
                v-for="item in finishedProductDepotList"
                :key="item.finishedProductDepot"
                :value="
                  item.finishedProductDepot +
                  '|' +
                  item.finishedProductDepotNo +
                  '|' +
                  item.finishedProductDepot_dictText
                "
                >{{ item.finishedProductDepotNo }}
                {{ item.finishedProductDepot_dictText }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="收发类别" prop="sendReceiveType">
            <a-select
              v-model="Form.sendReceiveType"
              @change="shoufaleibieMethod"
              showSearch
            >
              <a-select-option
                v-for="(item, index) in shoufaleibieList"
                :key="index"
                :value="item.id + '|' + item.name"
                >{{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="库存组织" prop="pk_calbody">
            <a-select
              v-model="Form.pk_calbody"
              @change="getpk_calbodyId"
              showSearch
              style="width: 100%"
            >
              <a-select-option
                v-for="item in InventoryOrganizationList"
                :key="item.id"
                :value="item.pkCalbody + '|' + item.bodyname"
              >
                {{ item.bodycode }}
                {{ item.bodyname }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="领料员" prop="picker">
            <a-select
              v-model="Form.picker"
              @change="getPickerId"
              @search="searchUserInfoList"
              showSearch
              style="width: 100%"
            >
              <a-select-option
                v-for="item in UserList"
                :key="item.userId"
                :value="item.workNo + '|' + item.userName"
              >
                {{ item.workNo }} {{ item.userName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="公司" prop="pkCorp_dictText">
            <a-tree-select
              v-model="Form.pkCorp_dictText"
              show-search
              style="width: 100%"
              allow-clear
              :tree-data="pk_corpList"
              @change="getpk_corpId"
            >
            </a-tree-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="库管员" prop="cwhsmanager">
            <a-select
              v-model="Form.cwhsmanager"
              showSearch
              style="width: 100%"
              @search="searchUserInfoList"
              @change="changecwhsmanager"
            >
              <a-select-option
                v-for="item in UserList"
                :key="item.userId"
                :value="item.workNo + '|' + item.userName"
              >
                {{ item.workNo }} {{ item.userName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            label="产成品分类"
            prop="finishedProductType_dictText"
          >
            <a-tree-select
              v-model="Form.finishedProductType_dictText"
              @change="setFinishGoodsType"
              :tree-data="finishGoodsTypeList"
              style="width: 100%"
            >
            </a-tree-select>
          </a-form-model-item>
        </a-col>
        <!-- <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="农户" prop="">
            <a-input
              v-model="Form.farmer"
              style="width: 100%"
              disabled
            ></a-input>
          </a-form-model-item>
        </a-col> -->
        <a-col :xl="6" :lg="6" :md="8" :sm="24" :xs="24">
          <a-form-model-item label="所属分厂" prop="ownedBranch_dictText">
            <a-tree-select
              v-model="Form.ownedBranch_dictText"
              style="width: 100%"
              :tree-data="ownedBranchList"
              showSearch
              @change="changeOwnedBranchTreeNode"
            >
            </a-tree-select>
          </a-form-model-item>
        </a-col>
      </a-row>

      <!-- 生成原单按钮组件 -->
      <productionMaterialReturn
        v-if="!updateTag"
        @select-data="setGoodsListInfoByOrigin"
      ></productionMaterialReturn>

      <!-- //TODO: -->
      <!-- 单据对应表格 -->
      <a-table
        :columns="columns"
        :data-source="dataSource"
        style="margin-top: 10px"
        :pagination="false"
        :scroll="{ x: 4000 }"
        :key="randomKey"
      >
        <!-- 仓库编码 -->
        <!--  <span slot="depotNo" slot-scope="text, record">
        <a-select
          v-model="record.depotNo"
          showSearch
          style="width: 100%"
          @change="setGoodsList(record.key)"
        >
          <a-select-option
            v-for="item in storageList"
            :key="item.depotNo"
            :value="item.depotNo + '|' + item.depotName"
          >
            {{ item.depotNo }} {{ item.depotName }}
          </a-select-option>
        </a-select>
      </span> -->
        <!-- 仓库名称 -->
        <span slot="depotId" slot-scope="text, record">
          <a-input-number v-model="record.depotId" />
        </span>
        <!-- 存货名称 -->
        <span slot="inventoryName" slot-scope="text, record">
          <a-select
            v-model="record.inventoryName"
            style="width: 100%"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="null"
            @search="handleSearch"
            @change="getInventoryInfo(record)"
            showSearch
          >
            <a-select-option
              v-for="(item, index) in goodsList"
              :key="index"
              :value="
                item.inventoryId +
                '|' +
                item.invcode +
                '|' +
                item.inventoryName +
                '|' +
                item.invspec +
                '|' +
                item.measname
              "
            >
              {{ item.invcode }} {{ item.inventoryName }}{{ item.invspec }}
            </a-select-option>
          </a-select>
        </span>
        <!-- 数量 -->
        <span slot="quantity" slot-scope="text, record">
          <a-input-number
            v-model="record.quantity"
            :min="0"
            :precision="precision"
          />
        </span>

        <!-- 出库日期 -->
        <span slot="deliveryDate" slot-scope="text, record">
          <a-date-picker
            @change="formatDeliveryDate(record)"
            v-model="record.deliveryDate"
            :defaultValue="moment(getCurrentData(), 'YYYY-MM-DD')"
            type="date"
            placeholder="请选择时间"
            style="width: 100%"
          />
        </span>
        <!-- 出菇领料金额 -->
        <span slot="amountOfFruitPicking" slot-scope="text, record">
          <a-input-number
            v-model="record.amountOfFruitPicking"
            :min="0"
            :precision="amountPrecision"
          />
        </span>
        <!-- 备注 -->
        <span slot="remark" slot-scope="text, record">
          <a-input v-model="record.remark"> </a-input>
        </span>
        <template slot="action" slot-scope="text, record">
          <span>
            <a @click="getGoodsShelves(record.key)">选择货架 </a>
          </span>
        </template>
      </a-table>
      <a-button
        style="width: 100%; margin-top: 16px; margin-bottom: 8px"
        type="dashed"
        icon="plus"
        @click="newMember"
        >添加</a-button
      >
      <div style="margin-top: 20px">
        <!-- 单据 -->

        ><!-- 顶部的信息 -->
        <a-row>
          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="负责人" prop="responsiblePerson">
              <a-select
                v-model="Form.responsiblePerson"
                style="width: 100%"
                showSearch
                @change="setResponsible_person"
              >
                <a-select-option
                  v-for="item in responsiblePersonList"
                  :key="item.userId"
                  :value="item.workNo + '|' + item.userName"
                >
                  {{ item.workNo }} {{ item.userName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>

          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="审核人" prop="inspector">
              <a-select
                v-model="Form.inspector"
                showSearch
                @change="setInspector"
                style="width: 100%"
              >
                <a-select-option
                  v-for="item in inspectorList"
                  :key="item.userId"
                  :value="item.workNo + '|' + item.userName"
                >
                  {{ item.workNo }} {{ item.userName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>

          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="审核日期" prop="">
              <a-date-picker
                v-model="Form.balance"
                type="date"
                style="width: 100%"
                disabled
              />
            </a-form-model-item>
          </a-col>

          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="制单人" prop="">
              <a-input disabled v-model="Form.singleProducerName"> </a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </div>
    </a-form-model>

    <!-- 提交按钮组  -->
    <div style="margin-top: 20px">
      <center>
        <!-- <a-button type="primary" style="margin-right: 20px"> 打印 </a-button> -->
        <a-button
          @click="submit"
          :disabled="isAntiAudit"
          style="margin-right: 20px"
        >
          保存
        </a-button>
        <a-button
          @click="Auditfunction"
          style="margin-right: 20px"
          :disabled="!isAntiAudit"
        >
          审核
        </a-button>
      </center>
    </div>

    <GoodsShelvesInfo
      :goodsShelvesTag="goodsShelvesTag"
      :tableKey="tableKey"
      :storageId="storageId"
      ref="goodShelvesInfo"
      @close-goodShelveInfo="closeGoodsShelves"
      @get-goodShelveInfo="getGoodShelveInfo"
    ></GoodsShelvesInfo>
  </a-card>
</template>

<script>
import axios from "axios";
import productionMaterialReturn from "@/components/common/productionMaterialReturn";
import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax(); // 公用接口
import GoodsShelvesInfo from "../../components/common/GoodsShelvesInfo";
// import { ZiDianBiaoHttp } from "@/services/modules/ZiDianBiao.js";
// const zdbHttp = new ZiDianBiaoHttp(); // 字典表

import moment from "moment";
import { mapState, mapGetters } from "vuex";

// 1. 导入
// import footerCommonBar from "../../components/common/footerCommonBar";

// 规则

// 物品信息表格
const columns = [
  {
    title: "序号",
    dataIndex: "key",
    key: "key",
    align: "center",
  },

  {
    title: "存货编码",
    dataIndex: "invcode",
    key: "invcode",
    align: "center",

    scopedSlots: { customRender: "invcode" },
  },
  {
    title: "存货名称",
    dataIndex: "inventoryName",
    key: "inventoryName",
    width: "10%",
    align: "center",
    scopedSlots: { customRender: "inventoryName" },
  },
  {
    title: "规格型号",
    dataIndex: "invspec",
    key: "invspec",
    align: "center",
  },
  {
    title: "单位",
    key: "measname",
    dataIndex: "measname",
    align: "center",
  },

  {
    title: "数量",
    key: "quantity",
    dataIndex: "quantity",
    align: "center",
    scopedSlots: { customRender: "quantity" },
  },
  {
    title: "单价",
    key: "unitPrice",
    dataIndex: "unitPrice",
    align: "center",
    scopedSlots: { customRender: "unitPrice" },
  },
  {
    title: "金额",
    key: "money",
    dataIndex: "money",
    align: "center",
    scopedSlots: { customRender: "money" },
  },
  {
    title: "源单单号",
    key: "sourceNumber",
    dataIndex: "sourceNumber",
    align: "center",
  },

  {
    title: "退库日期",
    key: "deliveryDate",
    dataIndex: "deliveryDate",
    align: "center",
    scopedSlots: { customRender: "deliveryDate" },
  },
  {
    title: "出菇领料金额",
    key: "amountOfFruitPicking",
    dataIndex: "amountOfFruitPicking",
    align: "center",
    scopedSlots: { customRender: "amountOfFruitPicking" },
  },
  {
    title: "货架",
    dataIndex: "goodsShelves",
    key: "goodsShelves",
    align: "center",
  },
  {
    title: "备注",
    dataIndex: "remark",
    key: "remark",
    align: "center",
    scopedSlots: { customRender: "remark" },
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    align: "center",
    fixed: "right",
    scopedSlots: { customRender: "action" },
  },
];

export default {
  // 2. 注册
  components: {
    productionMaterialReturn,
    GoodsShelvesInfo,
    // footerCommonBar,
  },
  computed: {
    // 获取本地数据
    ...mapState("user", { currUser: "info", currPost: "position" }),
    ...mapGetters({
      getDepsInfo: "user/getDepsInfo",
    }),
    // ...mapState("setting", ["isMobile"]),
  },
  data() {
    return {
      empty_: true,
      ownedBranchList: [], //所属分厂列表

      pk_corpList: [], // 公司列表

      u8c_array: [], //u8c传递数据表格的数据源
      arr: [], //
      GeneralBillVO: [], //需给用友传递的data
      ayyany: [],
      ayyanyany: [],

      // 子组件传参
      goodsShelvesTag: false,
      tableKey: 0,
      storageId: "",

      // rules2: {
      //   responsiblePerson: [
      //     {
      //       required: true,
      //       trigger: "change",
      //       message: "选择负责人",
      //     },
      //   ],
      //   inspector: [
      //     {
      //       required: true,
      //       trigger: "change",
      //       message: "选择审核人",
      //     },
      //   ],
      // },
      rules: {
        depotName: [
          {
            required: true,
            trigger: "blur",
            message: "选择仓库名称",
          },
        ],
        finishedProductDepot_dictText: [
          {
            required: true,
            trigger: "blur",
            message: "选择产成品仓库",
          },
        ],
        sendReceiveType: [
          {
            required: true,
            trigger: "blur",
            message: "选择收发类别",
          },
        ],
        pk_calbody: [
          {
            required: true,
            trigger: "blur",
            message: "选择库存组织",
          },
        ],
        picker: [
          {
            required: true,
            trigger: "blur",
            message: "选择领料员",
          },
        ],
        pkCorp_dictText: [
          {
            required: true,
            trigger: "blur",
            message: "公司不能为空",
          },
        ],
        cwhsmanager: [
          {
            required: true,
            trigger: "blur",
            message: "库管员不能为空",
          },
        ],
        ownedBranch_dictText: [
          {
            required: true,
            trigger: "change",
            message: "选择所属分厂",
          },
        ],
        finishedProductType_dictText: [
          {
            required: true,
            trigger: "change",
            message: "选择产成品分类",
          },
        ],
        responsiblePerson: [
          {
            required: true,
            trigger: "change",
            message: "选择负责人",
          },
        ],
        inspector: [
          {
            required: true,
            trigger: "change",
            message: "选择审核人",
          },
        ],
      },
      updateTag: false,
      isAntiAudit: false,
      // ----- 申请的表单内容信息 -----
      Form: {
        document: "", // 申请单号
        document_date: moment().format("YYYY-MM-DD"), // 单据日期 // 日期
        sendReceiveType: "", // 收发类别名称
        sendReceiveTypeId: "", // 收发类别Id
        finishedProductDepot: "", //产成品仓库ID
        cotherwhid: "", //仓库名称
        supplier: "", //供应商
        supplierId: "", //供应商Id
        responsiblePerson: "", // 负责人名称
        responsiblePersonId: "", // 负责人Id
        inspector: "", // 审核人名称
        inspectorId: "", // 审核人Id
        balance: moment().format("YYYY-MM-DD"), // 审核日期
        singleProducerName: this.$store.state.user.info.username, // 制单人名称
        singleProducerId: this.$store.state.user.info.id, // 制单人Id

        depotName: "", //仓库名称
        finishedProductDepot_dictText: "", //产成品仓库
        pkCalbody: "",
        pkCalbody_dictText: "", //库存组织
        picker: "", //领料员
        pkCorp_dictText: "", //公司
        cwhsmanager: "", //库管员
        ownedBranch_dictText: "", //所属分厂
      },

      // 字典表等数据

      storageList: [], // 仓库列表，所属仓库
      finishedProductDepotList: [], //产成品仓库
      supplierList: [], //供应商名称
      goodsList: [], // 存货列表
      shoufaleibieList: [], // 收发类别列表
      Auxiliary_Unitlist: [], // 辅助单位列表
      batchNumberList: [], // 批次号列表
      finishGoodsTypeList: [], //产成品分类列表

      customerNameList: [], //供应商列表
      farmerList: [], //农户列表

      InventoryOrganizationList: [], // 库存组织列表
      UserList: [], // 库管员列表

      responsiblePersonList: [], // 负责人列表
      inspectorList: [], // 审核人列表
      inspectorIdList: [], // 审核人Id列表

      // ------- 表格 --------
      // 格式
      layout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 15 },
      },
      precision: 2,
      amountPrecision: 3,
      // 列表
      columns,
      dataSource: [],

      randomKey: 0,
    };
  },
  // 生命周期函数
  mounted() {
    this.getfinishedProductDepot(); //产成品仓库
    // this.getApplyOrder(); // 获取申请单号
    this.getwarehouseInfo(); //获取仓库，所属仓库和产成品仓库接口
    this.judgeDocument(); //判断单据号是否为空
    this.getpk_corpList(); //公司
    this.getSendReceiveList(); //获取收发类别
    this.getSyncInventoryOrganizationList(); //获取库存组织
    this.getResponsiblePersonList(); // 获取负责人列表
    this.getInspectorList(); // 获取审核人
    this.initInfoMount();
    this.getFinishGoodsTypeList(); //获取产成品分类列表
    this.getownedBranchTree(); //获取分厂列表
  },
  watch: {
    $route: function (to) {
      if (to.path == "/productionMaterialOutCancel") {
        this.initInfoMount();
      }
     
    },
  },
  methods: {
    // ————判断单据号是否为空————
    judgeDocument() {
      setTimeout(() => {
        if (this.Form.document === "") {
          this.$message.error("未获取到单据号,请刷新页面重试");
        }
      }, 3000);
    },
    moment,

    async handleSearch(value) {
      var goodsList_invname = [];
      var goodsList_invspec = [];
      if (value.match(/^[ ]*$/)) {
        console.log("字符串为空或全空格");
      } else {
        this.goodsList = [];
        console.log("value", value);
        let query = "?name=" + value;
        console.log("query", query);
        if (value == "" || value == null) {
          this.goodsList = [];
        } else {
          await comHttp
            .getgetSearchInventoryInformationFile(query)
            .then((res) => {
              console.log("结果为", res);
              // this.goodsList = res.result;
              for (let i = 0; i < res.result.length; i++) {
                if (
                  res.result[i].invspec == "null" ||
                  res.result[i].invspec == null
                ) {
                  res.result[i].invspec = "";
                }
                if (
                  res.result[i].measname == "null" ||
                  res.result[i].measname == null
                ) {
                  res.result[i].measname = "";
                }
                let data = {
                  inventoryId: res.result[i].pkInvbasdoc, // 存货 id
                  invcode: res.result[i].invcode, //存货编码
                  inventoryName: res.result[i].invname, //存货名称
                  invspec: res.result[i].invspec, //规格型号
                  measname: res.result[i].measname, //单位
                };
                goodsList_invname.push(data);
              }
            });
          let queryInventoryBySpec = "?invspec=" + value;
          //规格型号模糊查询
          await comHttp
            .getqueryInventoryBySpec(queryInventoryBySpec)
            .then((res) => {
              console.log("结果规格型号模糊查询", res);

              goodsList_invspec = res.result.list.map((item) => {
                return {
                  inventoryId: item.pkInvbasdoc,
                  invcode: item.invcode,
                  inventoryName: item.invname,
                  invspec: item.invspec,
                  measname: item.measname,
                };
              });
            });
          //todo 合并去重函数
          await this.mergeArray(goodsList_invname, goodsList_invspec);
        }
      }
    },
    //todo 合并去重函数
    mergeArray(arr1, arr2) {
      let arrs = [...arr1, ...arr2];

      //根据inventoryId去重
      let map = new Map();
      for (let item of arrs) {
        if (!map.has(item.inventoryId)) {
          map.set(item.inventoryId, item);
        }
      }
      this.goodsList = [...map.values()];
    },
    // 获取存货信息
    async getInventoryInfo(record) {
      console.log("record11111111111111111111111111", record);
      let key = record.key;
      let target = this.dataSource.filter((item) => item.key === key)[0];
      console.log("target", target);
      // 分割字符串,取出来存货编码
      let array = target.inventoryName.split("|");
      console.log("array", array);
      target.inventoryId = array[0];
      target.invcode = array[1]; // 赋值给存货编码
      target.inventoryName = array[2]; // 赋值给存货名称

      if (array[3] != "null") {
        target.invspec = array[3]; // 赋值给规格型号
      } else {
        target.invspec = "";
      }

      if (array[4] != "null") {
        target.measname = array[4]; // 赋值给单位
      } else {
        target.measname = ""; // 赋值给单位
      }

      // console.log("目标物品信息:::::",target.goodsList)

      // 递归查询出来物品信息
      // let goodsInfomation = [];
      // for (let i = 0; i < this.goodsList.length; i++) {
      //   if (this.goodsList[i].inventoryNo == array[0]) {
      //     goodsInfomation = this.goodsList[i];
      //   }
      // }
      // console.log("物品信息::::", goodsInfomation);
      // target.standardModel = goodsInfomation.standardModel;
      // target.unit = goodsInfomation.unit;
      target.auxiliaryUnit = ""; // 重置辅助单位
      target.auxiliaryUnitId = ""; // 重置辅助单位
      target.giveawayId = 2; //

      // target.BatchList = await this.getBatchNumberList(
      //   target.depotId,
      //   goodsInfomation.inventoryId
      // ); // 获取批次列表
      /*  console.log(" target.position", target.position);
      if (target.position == undefined || target.position == "undefined") {
        target.BatchList = await this.getBatchNumberList(
          target.depotId,
          target.inventoryId
        );
      } else {
        target.BatchList = await this.getBatchNumberList(
          target.depotId,
          target.inventoryId,
          target.position
        );
      } */

      // console.log("批次号列表::::", target.BatchList);
      console.log("批次号列表::::", target.BatchList);
      //获取现存总数量
      // target.balance = await this.getBalanceTemp(
      //   // target.depotId, //仓库Id
      //   // target.inventoryId //存货 id
      //   record
      // );
    },
    /* ——————————模糊查询结束—————————————— */

    //获取客户字典表
    getfarmerId(value, options) {
      console.log("供应商::::", value, options.key);
      let array = value.split("|");
      console.log("array", array);
      // this.form.supplier_dictText = array[1];
      // this.form.supplier = array[2];
      this.$set(this.Form, "clientId_dictText", array[1]);
      this.$set(this.Form, "clientId", array[2]);
    },
    // 获取货架信息
    getGoodsShelves(key) {
      this.goodsShelvesTag = true;
      this.tableKey = key;
      this.storageId = "1001F3100000000002NY";

      setTimeout(() => {
        this.$refs.goodShelvesInfo.getGoodShelveInfo();
      }, 1000);
      //
    },

    // 关闭货架
    getGoodShelveInfo(key, goodsShelvesList) {
      console.log("序号和货架列表", key, goodsShelvesList);

      let str = "";
      goodsShelvesList.forEach((element) => {
        str = str + element.inOutShelf + ",";
      });
      str = str.substring(0, str.length - 1);
      this.$set(this.dataSource[key - 1], "goodsShelves", str);

      this.closeGoodsShelves();
    },
    // 关闭货架modal
    closeGoodsShelves() {
      this.goodsShelvesTag = false;
    },

    getCurrentData() {
      return new Date().toLocaleDateString();
    },
    // 申请单号
    getApplyOrder() {
      let queryPath = "?string=SCCKT-";
      comHttp.getOrder(queryPath).then((res) => {
        this.Form.document = res.message;
      });
    },

    // 仓库名称
    formDepotNameSelectChange(value) {
      let array = value.split("|");

      // 获取物品信息列表,根据仓库编码
      // let goodsList = this.getGoodSInfo(array[0]);
      console.log("仓库array", array);
      // 根据仓库查询物品信息,并存储到相应的物品信息表中
      this.Form.depotId = array[0];
      this.Form.depotName = array[2];

      for (let i = 0; i < this.dataSource.length; i++) {
        this.dataSource[i].depotId = array[0];
        this.dataSource[i].depotNo = array[1];
        this.dataSource[i].depotName = array[2];
        // this.dataSource[i].batchNumber = this.todayBatchNumber;
        // ---                                      ---//
        // this.getGoodSInfo2(this.dataSource[i], array[0]);
        // this.getPositionListById(this.dataSource[i], array[0]); // 获取仓位信息
      }
      console.log("仓库获取:::::", value);
    },

    getApplyStorage() {
      this.storageList = [];
      comHttp.getAllNumberName_new_forU8c().then((res) => {
        console.log("获取所有仓库", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            depotName: res.result[i].storname,
            depotNo: res.result[i].storcode,
            depotId: res.result[i].pkStordoc,
          };
          this.storageList.push(data);
        }
      });
    },
    getfinishedProductDepot() {
      this.finishedProductDepotList = [];
      comHttp.getAllNumberName_new_forU8c().then((res) => {
        console.log("获取所有仓库", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            finishedProductDepot_dictText: res.result[i].storname,
            finishedProductDepotNo: res.result[i].storcode,
            finishedProductDepot: res.result[i].pkStordoc,
          };
          this.finishedProductDepotList.push(data);
        }
      });
    },

    // 产成品仓库
    finishedProductDepotChange(value) {
      let array = value.split("|");

      // 获取物品信息列表,根据仓库编码
      // let goodsList = this.getGoodSInfo(array[0]);
      this.Form.finishedProductDepot = array[0];
      this.Form.finishedProductDepot_dictText = array[2];
      // 根据仓库查询物品信息,并存储到相应的物品信息表中
      for (let i = 0; i < this.dataSource.length; i++) {
        this.dataSource[i].finishedProductDepot = array[0];
        this.dataSource[i].finishedProductDepotNo = array[1];
        this.dataSource[i].finishedProductDepot_dictText = array[2];
        // this.dataSource[i].batchNumber = this.todayBatchNumber;
        // ---                                      ---//
        // this.getGoodSInfo2(this.dataSource[i], array[0]);
        // this.getPositionListById(this.dataSource[i], array[0]); // 获取仓位信息
      }
      console.log("产成品仓库仓库获取:::::", this.dataSource);
    },

    // 获取公司
    getpk_corpList() {
      comHttp.getpk_corpList().then((res) => {
        console.log("公司", res);
        this.pk_corpList = res.result;

        this.changeCorpData(this.pk_corpList);

        console.log(123124, this.pk_corpList);
      });
    },
    // 改变用友传递过来的数据为组件能识别的数据
    changeCorpData(Tree) {
      Tree.forEach((element) => {
        element["title"] = element.unitcode + " " + element.unitname;
        element["value"] = element.pkCorp + "|" + element.unitname;
        element["children"] = element.syncCompanyEntityList;
        element["key"] = element.id;

        if (element.children) {
          this.changeCorpData(element.children);
        }
      });
    },
    // 获取公司Id
    getpk_corpId(value, label, extra) {
      console.log("11111111111111", value);
      console.log("2222222222", label);
      console.log("33333333333", extra);
      let array = value.split("|");
      this.Form.pkCorp = array[0];
      this.Form.pkCorpName = array[1];
    },

    // 获取产成品分类列表
    getFinishGoodsTypeList() {
      comHttp.GetSaveCargoClassification().then((res) => {
        console.log("产成品分类列表", res);

        this.finishGoodsTypeList = res.result;
        this.changeFinishGoodsType(this.finishGoodsTypeList);
      });
    },
    // 改变用友传递过来的数据为组件能识别的数据
    changeFinishGoodsType(Tree) {
      Tree.forEach((element) => {
        element["title"] = element.invclassname;
        element["children"] = element.syncInventoryClassificationEntityList;
        element["key"] = element.invclassname;
        element["value"] = element.pkInvcl;

        if (element.children) {
          this.changeFinishGoodsType(element.children);
        }
      });
    },

    // 处理产成品分类
    setFinishGoodsType(key, value) {
      this.Form.finishedProductType = key;
      this.Form.finishedProductType_dictText = value;
      console.log("key======>", key);
      console.log("value======>", value);
      console.log("this.forafdslfdsfdsfd", this.Form.finishedProductType);

      // console.log("value11111111111", key);
      // let array = target.finishGoodsType.split("|");
      // // console.log("array===", array);
      // target.finishGoodsTypeId = array[0];
      // target.finishGoodsType = array[1];
      // console.log("target.finishGoodsTypeId", target);
    },

    // 获取分厂列表
    getownedBranchTree() {
      comHttp.getDepartmentList().then((res) => {
        // let tree = this.resetTree(res.result);
        console.log("获取部门树+++++++++++::::", res);
        this.ownedBranchList = res.result;
        this.changeownedBranchData(this.ownedBranchList);
      });
    },
    // 改变用友传递过来的数据为组件能识别的数据
    changeownedBranchData(Tree) {
      Tree.forEach((element) => {
        element["title"] = element.deptname;
        element["children"] = element.syncDepartmentFilesEntityList;
        element["key"] = element.pkDeptdoc;
        element["value"] = element.pkDeptdoc;

        if (element.children) {
          this.changeownedBranchData(element.children);
        }
      });
    },
    // 部门下拉框选择
    changeOwnedBranchTreeNode(key, value) {
      console.log("key", key);
      console.log("value", value);
      this.Form.ownedBranch_dictText = value[0];
      this.Form.ownedBranch = key;
      console.log("选择的值::::", this.Form.ownedBranch_dictText);
      console.log("ownedBranchId::::", this.Form.ownedBranch);
    },
    // 通过源单生成数据
    setGoodsListInfoByOrigin(data) {
      console.log("传递过来的数据:::::", data);
      // 给表单赋值
      this.Form.applicationDepot_dictText = data.applicationDepot_dictText; // 仓库名称
      // 仓库名称s
      this.Form.depotId = data.goodsList[0].depotId;
      this.Form.depotName = data.goodsList[0].depotId_dictText;
      // 产成品仓库名称
      this.Form.finishedProductDepot = data.finishedProductDepot;
      this.Form.finishedProductDepot_dictText =
        data.finishedProductDepot_dictText;
      // 库存组织
      this.Form.pkCalbody = data.pkCalbody;
      this.Form.pkCalbody_dictText = data.pkCalbody_dictText;
      // 公司
      this.Form.pkCorp_dictText = data.pkCorp_dictText;
      this.Form.pkCorp = data.pkCorp;

      // 产成品分类
      this.Form.finishedProductType_dictText =
        data.finishedProductType_dictText;
      this.Form.finishedProductType = data.finishedProductType;

      // 所属分厂
      this.Form.ownedBranch_dictText = data.ownedBranch_dictText;
      this.Form.ownedBranch = data.ownedBranch;

      // 库管员
      this.Form.cwhsmanagerid_dictText = data.cwhsmanagerid_dictText;
      this.Form.cwhsmanagerid = data.cwhsmanagerid;

      this.dataSource = data.goodsList; // 给列表赋值

      this.dataSource.forEach((element) => {
        element.remark = "";
        element.sourceNumber = data.document;
        element.inventoryName = element.inventoryId_dictText;
      });
    },

    // 路由跳转,设置初始化信息
    routerJumpSetInitInfo(id) {
      if (this.$route.query.isAntiAudit == "已反审核") {
        this.isAntiAudit = true;
      }
      this.updateTag = true;
      comHttp
        .getInOrOutStorageOrderAndGoodsInfoById("?id=" + id)
        .then((res) => {
          console.log(res);
          // this.Form = {};
          this.dataSource = [];
          /* ------------- 设置表单信息 -------------- */
          this.Form.id = res.result.list[0].id;
          this.Form.document = res.result.list[0].document;
          this.$set(
            this.Form,
            "document_date",
            res.result.list[0].documentDate
          );
          // 申请仓库
          this.Form.depotName = res.result.list[0].storname;
          this.Form.depotId = res.result.list[0].pkStordoc;
          this.Form.depotNo = res.result.list[0].storcode;

          // 产成品仓库
          this.Form.finishedProductDepot = res.result.list[0].storname;
          this.Form.finishedProductDepot_dictText =
            res.result.list[0].finishedProductDepot_dictText;
          // 库存组织
          this.Form.pk_calbody = res.result.list[0].pkCalbody_dictText;
          this.Form.pkCalbody = res.result.list[0].pkCalbody;
          // 领料员
          this.Form.pickerId = res.result.list[0].picker;
          this.Form.picker = res.result.list[0].picker_dictText;
          // 公司
          this.Form.pkCorp = res.result.list[0].pkCorp;
          this.Form.pkCorp_dictText = res.result.list[0].pkCorp_dictText;
          // 产成品分类
          this.Form.finishedProductType =
            res.result.list[0].finishedProductType;
          this.Form.finishedProductType_dictText =
            res.result.list[0].finishedProductTypeDictText;
          // 所属分厂
          this.Form.ownedBranch = res.result.list[0].ownedBranch;
          this.Form.ownedBranch_dictText =
            res.result.list[0].ownedBranch_dictText;
          this.Form.applicationDepot_dictText = res.result.list[0].storname; // 仓库名称
          // 负责人
          this.Form.responsiblePersonId = res.result.list[0].responsiblePerson;
          this.Form.responsiblePerson =
            res.result.list[0].responsiblePerson_dictText;
          // 库管员
          this.Form.cwhsmanagerid = res.result.list[0].cwhsmanagerid;
          this.Form.cwhsmanager = res.result.list[0].cwhsmanagerid_dictText;
          // 收发类别
          this.Form.sendReceiveTypeId = res.result.list[0].sendReceiveType;
          this.Form.sendReceiveType =
            res.result.list[0].sendReceiveType_dictText;
          // 部门
          this.Form.deptId_dictText = res.result.list[0].deptId_dictText;
          // 所属仓库

          // 客户
          this.Form.clientId_dictText = res.result.list[0].clientId_dictText;
          // 业务类型
          this.Form.cbiztype_dictText = res.result.list[0].cbiztype_dictText;

          // 库管员
          this.Form.cwhsmanagerid_dictText =
            res.result.list[0].cwhsmanagerid_dictText;

          // 库存组织
          this.Form.pkCalbody_dictText = res.result.list[0].pkCalbody_dictText;

          // 收发类别
          this.Form.sendReceiveType_dictText =
            res.result.list[0].sendReceiveType_dictText;

          // 审核人
          this.$set(this.Form, "inspectorId", res.result.list[0].inspector);
          this.$set(
            this.Form,
            "inspector",
            res.result.list[0].inspector_dictText
          );

          // // 制单人
          // this.Form.singleProducerName =
          //   res.result.list[0].singleProducer_dictText;

          let i = 0;
          res.result.list.forEach((element) => {
            let data = {
              id: element.twoId,
              key: i + 1,
              inventoryName: element.invname,
              invcode: element.invcode,
              depotId: element.depotId,
              invspec: element.invspec,
              measname: element.measname,
              auxiliaryUnit: element.auxiliaryUnit_dictText,
              sourceNumber: element.sourceNumber,
              remark: element.remark,
              quantity: element.quantity,
            };
            i = i + 1;
            this.dataSource.push(data);
          });
          this.sortArr(res.result.list, "depotNo");
        });
    },
    // this.u8c_array数组根据仓库编码筛选，将相同的仓库编码放在一个数组里
    sortArr(arr, str) {
      var newArr = [],
        newArrItem = [],
        // 临时变量
        tempArr = [];
      // 按照特定的参数将数组排序将具有相同值的排在一起
      arr = arr.sort(function (a, b) {
        var s = a[str],
          t = b[str];

        return s < t ? -1 : 1;
      });

      if (arr.length) {
        tempArr = arr[0][str];
      }

      // 将相同类别的对象添加到统一个数组
      for (var i in arr) {
        if (arr[i][str] === tempArr) {
          console.log("tempArr", tempArr);
          newArrItem.push(arr[i]);
        } else {
          tempArr = arr[i][str];
          newArr.push(newArrItem);
          newArrItem = [arr[i]];
        }
      }
      // 将最后的内容推出新数组
      newArr.push(newArrItem);
      this.u8c_array = newArr;
      console.log("u8c_arr", this.u8c_array);
    },
    // 点击提交按钮，将产成品入库单传递给用友
    save_u8c() {
      for (let i = 0; i < this.u8c_array.length; i++) {
        console.log("i", i);

        this.arr = [];
        for (let j = 0; j < this.u8c_array[i].length; j++) {
          console.log("j", j);
          console.log("this.u8c_array[i].length", this.u8c_array[i].length);
          let data = {
            cinventoryid: this.u8c_array[i][j].invcode, //存货ID √
            noutnum: this.u8c_array[i][j].quantity, //实出数量 √
            vsourcebillcode: this.u8c_array[i][j].document, //单据号 √
            vnotebody: this.u8c_array[i][j].remark, // 行备注 √
            dbizdate: moment(this.u8c_array[i][j].deliveryDate).format(
              "YYYY-MM-DD"
            ), //出库日期（业务日期）√
            pk_defdoc4: this.u8c_array[i][j].amountOfFruitPicking, //出菇领料金额
          };
          this.arr.push(data);
          console.log("this.arr", this.arr);
        }
        this.ayyany = {
          parentvo: {
            cdispatcherid: this.u8c_array[i][0].sendReceiveType1_dictText, //收发类别名称 √
            coperatorid: this.u8c_array[i][0].singleProducerByCode_dictText, //制单人  √
            cbizid: this.u8c_array[i][0].workNO, //业务员ID（领料员） √
            cwhsmanagerid: this.u8c_array[i][0].cwhsmanagerid1_dictText, //库管员ID  √
            cdptid: this.u8c_array[i][0].cdptidByCode_dictText, //部门 √
            cwarehouseid: this.u8c_array[i][0].storcode, //仓库id  √
            dbilldate: moment(this.u8c_array[i][0].documentDate).format(
              "YYYY-MM-DD"
            ), //单据日期
            pk_calbody: "100001", //库存组织PK=仓库编号
            pk_corp: "1001", //公司
            vreceiptcode: this.u8c_array[i][0].document, //单据号 √
            vbillcode: this.u8c_array[i][0].document, //!单据号 √
            vuserdef5: this.u8c_array[i][0].finishedProductType1_dictText, // 自定义项5-产成品分类 √
            vuserdef6: this.u8c_array[i][0].finishedProductDepot1_dictText, // 自定义项6-产成品仓库 √
            vuserdef3: this.u8c_array[i][0].farmer1_dictText, //自定义项3-农户 √
            vnote: "", //备注 √
          },
          childrenvo: this.arr,
        };

        this.ayyanyany.push(this.ayyany);
      }
      console.log("this.GeneralBillVO::::", this.ayyanyany);
      // u8c接口
      axios({
        headers: {
          "Access-Control-Allow-Origin": "*",
          trantype: "code",
          "Content-Type": "application/json",
          usercode: "13355262265",
          password: "5ef208ee90e5504a7b569ebbd6342634",
          system: "test",
        },
        method: "post",
        url: "/api/u8cloud/api/ic/materialout/save/sign",
        data: {
          GeneralBillVO: this.ayyanyany,
        },
      }).then((response) => {
        console.log("response====>", response);
        console.log(response.data.status, 666666666666666666);
        let _data = JSON.parse(response.data.data);
        console.log(_data, 7777777777777);

        if (response.data.status === "success") {
          this.$message.success("同步成功");
          this.updateSucessRecordTag = true;
          this.Form.isSynchronized = "已同步";
          this.postSynchronized("已同步");

          // 跳转回列表页面
          this.$router.push("/productionMaterialOutCancelList");
          // alert("同步成功！");
        } else {
          // this.$message.success("同步失败");
          this.$message.error(response.data.errormsg);
        }
      });
    },
    //是否同步标志位
    postSynchronized(isSynchronized) {
      let data = {
        id: this.Form.id,
        isSynchronized: isSynchronized,
      };
      console.log(data, "11111111111");
      comHttp.updateInOrOutStorageOrder(data).then((res) => {
        console.log(res, 11111111111111111111);
      });
    },
    //是否反审核标志位
    update_audit(isAntiAudit) {
      let data = {
        id: this.Form.id,
        isAntiAudit: isAntiAudit,
      };
      console.log(data, "2222222222222");
      comHttp.updateInOrOutStorageOrder(data).then((res) => {
        console.log(res, 2222222222222);
      });
    },
    //审核标志位
    update_Mark(isOrNo) {
      let data = {
        id: this.Form.id,
        auditMark: isOrNo,
        balance: "",
      };
      this.Form.balance = "";
      console.log(data, "33333333333333333");
      comHttp.updateInOrOutStorageOrder(data).then((res) => {
        console.log(res, 33333333333333);
      });
    },
    // 新增提交
    addSubmit() {
      let array = [];
      console.log("array=============", this.dataSource.length);

      this.dataSource.forEach((element) => {
        let data = {
          objectInformationId: element.objectInformationId,
          inventoryId: element.inventoryId,

          // auxiliaryUnit: element.auxiliaryUnit,
          quantity: element.quantity,
          sourceNumber: element.sourceNumber,
          remark: element.remark, //备注
          depotId: element.depotId, // 仓库名称
          unitPrice: element.unitPrice, // 单价
          money: element.money, // 金额
          deliveryDate: element.deliveryDate, //出库日期
          amountOfFruitPicking: element.amountOfFruitPicking, //生产领料数量

          // storageUnit：this.Form.所属仓库
        };
        array.push(data);
      });
      console.log("array", array);
      //  let  array
      let submitData = {
        balance: this.Form.document_date,
        auditMark: 2, // 未审核是 1 , 已审核是 2
        bookkeepingMark: 2,
        inOutCategoryIdentification: 9, // 生产材料退库
        inOutIdentification: 3, // 退库

        cotherwhid: this.Form.depotId, //仓库名称
        finishedProductDepot: this.Form.finishedProductDepot, // 产成品仓库
        sendReceiveType: this.Form.sendReceiveTypeId, // 收发类别

        pkCalbody: this.Form.pkCalbody, //库存组织
        picker: this.Form.pickerId, //领料员
        pkCorp: this.Form.pkCorp, //公司Id
        cwhsmanagerid: this.Form.cwhsmanagerid, //库管员
        finishedProductType: this.Form.finishedProductType, //产成品分类
        ownedBranch: this.Form.ownedBranch, //所属分厂
        document: this.Form.document, // 单据号
        documentDate: moment(this.Form.document_date).format("YYYY-MM-DD"), // 单据日期

        inspector: this.Form.inspectorId, // 审核人
        singleProducer: this.Form.singleProducerId, // 制单人
        responsiblePerson: this.Form.responsiblePersonId, // 负责人
        warehouseObjectInformationEntities: array,
      };

      console.log("要提交的数据为:::::", submitData);
      if (this.dataSource.length != 0) {
        this.checkempty(submitData); //校验
        if (this.empty_ === true) {
          // 保存退库信息
          comHttp.addInOrOutStorageOrderAndGoods(submitData).then((res) => {
            if (res.success == true) {
              this.$message.success("保存成功");

              this.initInfo();
              this.saveGoodsShelvesInfo(res.result.list);
            } else {
              this.$message.error("保存失败");
            }
          });
        }
      } else {
        this.$message.error("请添加列表信息!");
      }
    },
    //  校验是否为空
    checkempty(submitData) {
      this.empty_ = true;
      console.log("11111", submitData);
      var message = []; //提示信息
      /*  if (this._xxx.length === 0) {
        this.empty_ = false;
        message.push("请添加列表信息!" + "\xa0\xa0\xa0");
      } */
      /* if (this.DataSource.element.length ===0) {
        this.empty_ = false;
        message.push("请添加列表信息!" + "\xa0\xa0\xa0");
      } */
      this.dataSource.forEach((element) => {
        console.log("element", element);
        if (!element.depotId) {
          this.empty_ = false;
          message.push("请再选择一次仓库!" + "\xa0\xa0\xa0");
        }
        if (!element.inventoryName) {
          this.empty_ = false;
          message.push("存货信息不能为空!" + "\xa0\xa0\xa0");
        }
        if (!element.quantity) {
          this.empty_ = false;
          message.push("存货数量不能为空!" + "\xa0\xa0\xa0");
        }
      });

      if (!this.empty_) {
        this.$message.error(message);
      }
    },
    // 保存货架信息
    saveGoodsShelvesInfo(data) {
      let array = [];
      for (let i = 0; i < data.length; i++) {
        let submitData = {
          objectId: data[i].id,
          positionId: this.DataSource[i].position,
          inOutShelf: this.dataSource[i].goodsShelves.split(","),
          isOut: 1,
        };
        array.push(submitData);
      }
      console.log("提交数据", array);
      comHttp.saveShelfInfo(array).then((res) => {
        console.log("213", res);
      });
    },
    // 修改提交
    updateSubmit() {
      let array = [];
      this.dataSource.forEach((element) => {
        let data = {
          id: element.id,
          quantity: element.quantity,
          remark: element.remark,
          amountOfFruitPicking: element.amountOfFruitPicking, //生产领料数量
        };
        array.push(data);
      });

      let submitForm = {
        id: this.Form.id,
        inspector: this.Form.inspectorId,
        responsiblePerson: this.Form.responsiblePersonId, // 负责人
        sendReceiveType: this.Form.sendReceiveTypeId, // 收发类别
        picker: this.Form.pickerId, //领料员
        cwhsmanagerid: this.Form.cwhsmanagerid, //库管员updateSubmit
        // documentDate: this.Form.document_date, //库管员updateSubmit

        // sendReceiveType: this.Form.sendReceiveTypeId, // 收发类别
        documentDate: moment(this.Form.document_date).format("YYYY-MM-DD"),
        warehouseObjectInformationEntities: array,
      };

      // 修改全部的信息
      comHttp.updateInOrOutStorageOrderAndGoods(submitForm).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.$message.success("修改成功");
          this.save_u8c();
          this.$router.push("/productionMaterialOutCancelList");
        } else {
          this.$message.error("修改失败");
        }
      });
    },
    //审核修改
    Auditfunction() {
      let array = [];
      this.dataSource.forEach((element) => {
        let data = {
          id: element.id,
          quantity: element.quantity,
          remark: element.remark,
          amountOfFruitPicking: element.amountOfFruitPicking, //生产领料数量
        };
        array.push(data);
      });

      let submitForm = {
        id: this.Form.id,
        inspector: this.Form.inspectorId,
        responsiblePerson: this.Form.responsiblePersonId, // 负责人
        sendReceiveType: this.Form.sendReceiveTypeId, // 收发类别
        picker: this.Form.pickerId, //领料员
        cwhsmanagerid: this.Form.cwhsmanagerid, //库管员
        // sendReceiveType: this.Form.sendReceiveTypeId, // 收发类别
        // documentDate: moment(this.Form.document_date).format("YYYY-MM-DD"),
        warehouseObjectInformationEntities: array,
      };

      // 修改全部的信息
      comHttp.updateInOrOutStorageOrderAndGoods(submitForm).then((res) => {
        console.log(res);
        if (res.code == 200) {
          //标志位修改
          this.postSynchronized("未同步");
          this.update_audit("未反审核");
          this.update_Mark(1);
          this.$message.success("修改成功");
          this.save_u8c();
          this.$router.push("/productionMaterialOutCancelList");
        } else {
          this.$message.error("修改失败");
        }
      });
    },

    // 提交
    submit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          //  这是新增提交
          if (this.updateTag == false) {
            this.addSubmit();
          } else {
            // 这是修改提交
            this.updateSubmit();
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 客户模糊搜索
    searchFarmer(value) {
      if (value == "") {
        this.$message.error("请输入客户名称！");
      } else if (value == " ") {
        value = "";
        console.log("value", value);
        this.$message.error("请输入真实数据！");
      } else {
        this.customerNameList = [];
        let data = "?customerName=" + value + "&custflag=0,2";
        comHttp.getCustomerInfoByName(data).then((res) => {
          console.log("res", res);
          for (let i = 0; i < res.result.length; i++) {
            let data = {
              id: res.result[i].pkCumandoc,
              customerCode: res.result[i].custcode,
              name: res.result[i].custname,
            };
            this.farmerList.push(data);
          }
        });
      }
    },
    // 客户选择的处理函数
    changeFarmer(value) {
      console.log("客户选择处理函数", value);
      let array = value.split("|");
      this.Form.farmerCode = array[0]; //客户编码
      this.Form.farmer = array[1]; //客户名称
      this.Form.farmerId = array[2]; //客户Id
      console.log("this.form.customerId", this.Form.customerId);
      let id = array[2]; //客户id
      console.log("id", id);
    },
    // 客户模糊搜索
    searchCustomer(value) {
      if (value == "") {
        this.$message.error("请输入客户名称！");
      } else if (value == " ") {
        value = "";
        console.log("value", value);
        this.$message.error("请输入真实数据！");
      } else {
        this.customerNameList = [];
        let data = "?customerName=" + value + "&custflag=3,1";
        comHttp.getCustomerInfoByName(data).then((res) => {
          console.log("res", res);
          for (let i = 0; i < res.result.list.length; i++) {
            let data = {
              id: res.result.list[i].pkCumandoc,
              customerCode: res.result.list[i].custcode,
              name: res.result.list[i].custname,
            };
            this.customerNameList.push(data);
          }
        });
      }
    },
    // 客户选择的处理函数
    changeCustomer(value) {
      console.log("客户选择处理函数", value);
      let array = value.split("|");
      this.Form.supplierCode = array[0]; //客户编码
      this.Form.supplier = array[1]; //客户名称
      this.Form.supplierId = array[2]; //客户Id
      console.log("this.form.customerId", this.Form.supplierId);
      let id = array[2]; //客户id
      console.log("id", id);
    },

    // 获取库存组织列表
    getSyncInventoryOrganizationList() {
      comHttp.getSyncInventoryOrganizationList().then((res) => {
        console.log("库存组织", res);
        this.InventoryOrganizationList = res.result;
      });
    },
    // 获取库存组织Id
    getpk_calbodyId(value) {
      // this.Form.pk_calbodyId = options.key;
      // console.log(this.Form.pk_calbodyId, 222222222);
      console.log("value", value);
      let array = value.split("|");
      this.Form.pkCalbody = array[0];
      console.log("this.Form.pkCalbody", this.Form.pkCalbody);
    },

    // 库管员列表
    getcwhsmanagerId(value, option) {
      this.Form.cwhsmanagerid = option.key;
      console.log("this.getcwhsmanagerId", this.Form.cwhsmanagerid);
    },

    // 查询人员信息列表
    searchUserInfoList(value) {
      this.UserList = [];
      this.workNoList = [];
      if (value != "") {
        let queryPath = "?username=" + value;
        comHttp.getUserInfoByUserName(queryPath).then((res) => {
          for (let i = 0; i < res.result.list.length; i++) {
            if (!this.workNoList.includes(res.result.list[i].workNo)) {
              let data = {
                userName: res.result.list[i].username,
                userId: res.result.list[i].id,
                workNo: res.result.list[i].workNo,
              };
              this.UserList.push(data);
              this.workNoList.push(res.result.list[i].workNo);
            }
          }
        });
      }
    },

    // 领料员列表处理函数
    getPickerId(value, option) {
      this.Form.pickerId = option.key;
      this.Form.picker = value;
    },
    changecwhsmanager(value, option) {
      this.Form.cwhsmanagerid = option.key;
      this.Form.cwhsmanager = value;
    },

    // 页面和路由跳转加载函数
    initInfoMount() {
      if (typeof this.$route.query.Id != "undefined") {
        console.log("--------- 更新视图 销售退库  ----------");
        this.routerJumpSetInitInfo(this.$route.query.Id);
      } else {
        this.initInfo();
      }
    },
    // 初始化加载信息
    initInfo() {
      this.Form = {
        balance: moment().format("YYYY-MM-DD"),
        document: "", // 单据号
        document_date: moment().format("YYYY-MM-DD"),
        singleProducerName: this.$store.state.user.info.username, // 制单人名称
        singleProducerId: this.$store.state.user.info.id, // 制单人Id
      };
      this.dataSource = [];
      this.getApplyOrder();
    },
    // 获取所属仓库,表格触发事件
    getstorageUnitId(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      let array = target.storageUnit.split("|");
      target.storageUnitNo = array[0]; // 仓库id
      target.storageUnit = array[1]; // 仓库名称

      let SotrageInfo = this.storageList.filter(
        (item) => item.depotNo === array[0]
      )[0];
      target.storageUnitId = SotrageInfo.depotId;
      console.log("表格所属仓库::::", target.storageUnitId);
    },

    // 所属仓库，仓库名称，产成品仓库
    getwarehouseInfo() {
      comHttp.getStorageName().then((res) => {
        console.log("仓库名称列表", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            depotName: res.result[i].storname,
            depotNo: res.result[i].storcode,
            depotId: res.result[i].pkStordoc,
          };
          this.storageList.push(data);
        }
      });
    },

    // 获取收发类别列表
    getSendReceiveList(queryPath = "") {
      console.log("hfougdiuy");
      comHttp.getReceiveSendTypeListAll(queryPath).then((res) => {
        console.log("收发类别列表", res);
        this.shoufaleibieList = res.result;
      });
    },

    //收发类别触发函数
    shoufaleibieMethod(value) {
      console.log("收发类别触发函数value", value);
      let array = value.split("|");
      console.log("array", array);
      // 表格自动填充所属单位
      this.Form.sendReceiveTypeId = array[0]; //收发类别id
      this.Form.sendReceiveType = array[1]; //收发类别name
    },

    // 格式化出库日期
    formatDeliveryDate(record) {
      let target = this.DataSource.filter((item) => item.key === record.key)[0];
      target.deliveryDate = moment(target.deliveryDate).format("YYYY-MM-DD");
      console.log("修改好的时间为::::", target.deliveryDate);
    },

    // 获取负责人列表
    getResponsiblePersonList() {
      const roleName = "仓库负责人员";
      let queryPath = "?roleName=" + roleName;
      comHttp.getUserRoleNameByUserNameId(queryPath).then((res) => {
        // console.log(res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            userName: res.result[i].userName,
            userId: res.result[i].userId,
            workNo: res.result[i].workNo,
          };
          this.responsiblePersonList.push(data);
        }
      });
    },
    // 设置负责人id
    setResponsible_person(value, options) {
      let array = value.split("|");
      this.Form.responsiblePerson = array[1];
      this.Form.responsiblePersonId = options.key;
    },
    // 获取审核人
    getInspectorList() {
      const roleName = "仓库审核人员";
      let queryPath = "?roleName=" + roleName;
      comHttp.getUserRoleNameByUserNameId(queryPath).then((res) => {
        // console.log(res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            userName: res.result[i].userName,
            userId: res.result[i].userId,
            workNo: res.result[i].workNo,
          };
          this.inspectorList.push(data);
          this.inspectorIdList.push(res.result[i].userId);
        }
        if (this.inspectorIdList.indexOf(this.$store.state.user.info.id) > -1) {
          // 按钮状态改变:::::
          console.log(this.ExamineDisplay);
          this.ExamineDisplay = false;
        } else {
          this.ExamineDisplay = true;
        }
      });
    },
    // 设置审核人id
    setInspector(value, options) {
      let array = value.split("|");
      this.Form.inspector = array[1];
      this.Form.inspectorId = options.key;
    },

    // 表格添加新的一条记录
    newMember() {
      console.log("增加一条记录");
      this.savebalance = Infinity;
      this.dataSource.push({
        key: this.dataSource.length + 1,
        isNew: true,

        depotNo: "", // 仓库编码、
        depotId: this.Form.depotId, //仓库id
        quantity: "", //数量
        unitPrice: "", //单价
        invcode: "", // 存货编码
        invname: "", //  存货名称
        inventoryName: "",
        // standardModel: "", //规格型号
        invspec: "", //规格型号
        measname: "", // 单位
        position: "", // 仓位
        sourceNumber: "", // 源单单号（外键）
        batchNumber: "", // 批次号
        giveaway: "2", // 是否赠品
        remark: "", // 备注
        goodsList: [], // 物品信息列

        deliveryDate: moment().format("YYYY-MM-DD"), //入库日期
      });
      console.log("this.dataSource", this.dataSource);
    },
  },
};
</script>

<style></style>
